package firstcontent.reference;

import java.lang.ref.SoftReference;

/**
 * @Author: fxy
 * @Date: 2022/02/25/8:26
 * @Description: -Xms10m -Xmx10m -XX:+PrintGCDetails
 */
public class SoftReferenceTest {

    public static class User{
        public int id;
        public String name;
        public byte[] bytes;
        public User(int id,String name,int size){
            this.id = id;
            this.name = name;
            bytes = new byte[size];
        }

        @Override
        public String toString() {
            return "User{" +
                    "id=" + id +
                    ", name='" + name + '\'';
        }
    }

    public static void main(String[] args) {
        SoftReference<User> userSoftRef = new SoftReference<>(new User(1,"yun",5*1024*1024));
        System.gc();
        System.out.println(userSoftRef.get());
        try {
            /**
             * 这里进行了两次full gc
             * 第一次没有回收软引用对象
             * 第二次发现不回收软引用没有空间，于是软引用对象被回收
             */
            byte[] bytes = new byte[5*1024*1024];
        }catch (Throwable e){
            /**
             * 内存不够时，软引用对象被回收
             */
            e.printStackTrace();
        }
        System.out.println(userSoftRef.get());
    }
}
